import '../styles/components.scss'
import 'react-quill/dist/quill.snow.css'
import { Form, Button, Input, Space, message, Card, Radio, DatePicker, Upload, InputNumber} from 'antd'
import { PlusOutlined} from '@ant-design/icons'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { useStore } from '@/store'
import ReactQuill from 'react-quill'
import { useState, useRef, useEffect } from 'react'
import {server} from '@/static/server'
import { forms } from '@/static/forms';
import locale from 'antd/es/date-picker/locale/zh_CN'
import SelectOption from '@/components/SelectOption'


const { RangePicker } = DatePicker
const { TextArea } = Input;


const CustomForm = (props) => {
    const [params] = useSearchParams()
    const id = params.get("id")
    const api = params.get("api")

    const customForm = forms[api] ? forms[api] : []
    const { operateStore } = useStore()

  
    // 存放上传图片的列表
    const [fileList, setFileList] = useState([])

    // 这个函数的执行分阶段 是从updating到done的过程
    // 这个过程只要上传图片内容发生变化就会不断执行直到全部上传完毕
    // 使用useRef声明一个暂存仓库
    const cacheImgList = useRef([])
    const onUploadChange = ({ fileList }) => {
        // 同时把图片列表存入仓库一份
        // 这里关键位置:需要做数据格式化
        const formatList = fileList.map(file => {
            // 上传完毕 做数据处理
            if (file.response) {
                return {
                    url: server.url+file.response.data
                }
            }
            // 否则在上传中时，不做处理
            return file
      })
      setFileList(formatList)
      cacheImgList.current = formatList
    }

    const navigate = useNavigate()
    const [paramsProcess, setParamsProcess] = useState({})
    const [selectValue, setSelectValue] = useState()
    const onFinish = async (values) => {
        if(fileList && fileList.length > 0){
            setParamsProcess({
                type: values.type,
                images: fileList.map(item => item.url)
            })
        }

        const params = {
            ...values,
            ...paramsProcess,
            ...selectValue
        }
        if (id) {
            const edit_params = {
                ...paramsProcess,
                ...selectValue,
                ...values
            }
            const res = await operateStore.modifyItem(api, id, edit_params)
            if(res.return_code === "1111"){
                return message.error(res.return_msg);
            }
        }else{
            const res = await operateStore.createItem(api, params)
            if(res.return_code === "1111"){
                return message.error(res.return_msg);
            }
        }
       
        navigate(`/list/${api}`)
        message.success(`${id ? '更新成功' : '创建成功'}`)
    }
    const [form] = Form.useForm()
    useEffect(() => {
        const loadDetail = async () => {
          const data = await operateStore.getItem(api, id)
          // 表单数据回填
          form.setFieldsValue({ ...data})

          // 设置Select组件的值
          setSelectValue(data)

          // 回填upload
          const formatImgList = data.cover ? data.cover.images.map(url => ({ url })) : []
          setFileList(formatImgList)
          // 暂存列表里也存一份
          cacheImgList.current = formatImgList
        }
        // 必须是编辑状态 才可以发送请求
        if (id) {
          loadDetail()
        }
      }, [api, id, form, operateStore])
    
    return (
        <div className="coustom_form">
        {customForm && customForm.length > 0 && (
            <Card title={id ? "编辑" : "新建"}>

                <Form
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 16 }}
                    initialValues={{ type: 1, content: '' }}
                    onFinish={onFinish}
                    form={form}
                >
                    {customForm.map(item => {
                        if(item.form.type === "Select"){
                           return <Form.Item
                                    key={item.name}
                                    label={item.label}
                                    name={item.name}
                                    rules={item.rules}
                                    className={item.className}
                                  >
                                    <SelectOption item={item} selectValue={selectValue} setSelectValue={setSelectValue} />
                                  </Form.Item>
                        }else if(item.form.type === "Radio"){
                            return <Form.Item
                                        key={item.name}
                                        label={item.label}
                                        name={item.name}
                                    >   
                                        <Radio.Group
                                            options={item.form.values}
                                            optionType="button"
                                            buttonStyle="solid"
                                            defaultValue={item.form.defaultValue}
                                        />
                                    </Form.Item>
                        }else if(item.form.type === "DatePicker"){
                            return <Form.Item
                                        key={item.name}
                                        label={item.label}
                                        name={item.name}
                                        rules={item.rules}
                                        className={item.className}  
                                    >
                                        <DatePicker locale={locale} 
                                                    style={item.form.style}  
                                                    format={item.form.format}
                                                    showTime={item.form.showTime} />
                                    </Form.Item>
                        }else if(item.form.type === "RangePicker"){
                            return <Form.Item
                                        key={item.name}
                                        label={item.label}
                                        name={item.name}
                                        rules={item.rules}
                                        className={item.className}
                                    >
                                        <RangePicker locale={locale} 
                                                     style={item.form.style} 
                                                     format={item.form.format}
                                                     showTime={item.form.showTime}/>
                            </Form.Item>
                        }else if (item.form.type === "ReactQuill"){
                            return <Form.Item
                                        key={item.name}
                                        label={item.label}
                                        name={item.name}
                                        rules={item.rules}
                                        className={item.className}
                                    >
                                        <ReactQuill theme="snow" />
                                    </Form.Item>
                        }else if(item.form.type === "Upload"){
                            return <Form.Item 
                                        key={item.name}
                                        label={item.label}
                                        name={item.name}
                                        rules={item.rules}
                                        className={item.className}
                                    >
                                        <Upload
                                            name="file"
                                            listType="picture-card"
                                            className="avatar-uploader"
                                            showUploadList
                                            action={item.form.action}
                                            fileList={fileList}
                                            onChange={onUploadChange}
                                            multiple={item.form.count > 1}
                                            maxCount={item.form.count}
                                        >
                                            <div style={{ marginTop: 8 }}>
                                            <PlusOutlined />
                                            </div>
                                        </Upload>
                            </Form.Item>
                        }else if(item.form.type === "Input.Password"){
                            return <Form.Item
                                        key={item.name}
                                        label={item.label}
                                        name={item.name}
                                        rules={item.rules}
                                        className={item.className}
                                    >
                                        <Input.Password autoComplete="true" placeholder={item.placeholder} style={item.form.style} />
                            </Form.Item>
                        }else if(item.form.type === "TextArea"){
                            return <Form.Item
                                        key={item.name}
                                        label={item.label}
                                        name={item.name}
                                    >
                                        <TextArea rows={item.form.rows} />
                            </Form.Item>
                        }else if(item.form.type === "InputNumber"){
                            return <Form.Item
                                key={item.name}
                                label={item.label}
                                name={item.name}
                                rules={item.rules}
                                className={item.className}
                            >
                                <InputNumber style={item.form.style} />
                            </Form.Item>
                        }else{
                            return <Form.Item
                                        key={item.name}
                                        label={item.label}
                                        name={item.name}
                                        rules={item.rules}
                                        className={item.className}
                                    >
                                        <Input placeholder={item.placeholder} style={item.form.style} />
                                   </Form.Item>
                        }
                    })}
                    <Form.Item wrapperCol={{ offset: 4 }}>
                        <Space>
                        <Button size="middle" type="primary" htmlType="submit">保存</Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Card>
        )}
    </div>
  )
}


export default CustomForm